import { asyncRouterMap, constantRouterMap } from '@/router' // 导入路由匹配规则
import { hasPermissionOfRouteName } from '@/utils/permission'

const permission = {
  state: {
    routers: constantRouterMap, // 主路由规则 ，侧边导航栏拿到后进行遍历生成侧导航栏
    addRouters: [] // 业务路由规则 // 在路由导航守卫上，就将业务路由挂载到了主路由身上
  },
  mutations: {
    SET_ROUTERS: (state, routers) => { // 将业务路由合并到主路由上
      state.addRouters = routers // 保存业务路由匹配规则
      state.routers = constantRouterMap.concat(routers) // 总的路由匹配规则
    }
  },
  actions: {
    GenerateRoutes ({ commit }, data) { // 在路由导航守卫上，就将业务路由挂载到了主路由身上
      return new Promise(resolve => {
        /// 动态路由
        /// 内部函数递归路由 筛选需要的数据
        // function filterAsyncRouter(routers) {
        //   return routers.filter(route => {
        //     if (hasPermissionOfRouteName(route.name)) {
        //       if (route.children && route.children.length) {
        //         route.children = filterAsyncRouter(route.children)
        //       }
        //       return true
        //     } else {
        //       return false
        //     }
        //   })
        // }
        // let accessedRouters = filterAsyncRouter(asyncRouterMap)
        // commit('SET_ROUTERS', accessedRouters)
        commit('SET_ROUTERS', asyncRouterMap) // 业务的路由匹配规则对象
        resolve()
      })
    }
  }
}

export default permission
